<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>JS事件循环 | 黑不溜球de博客么么哒</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="javascriptjavascript从诞生之日起就是一门单线程的非阻塞的脚本语言。这是由其最初的用途来决定的：与浏览器交互。  单线程：javascript代码在执行的任何时候，都只有一个主线程来处理所有的任务  非阻塞：执行异步任务的时候，主线程这个任务，然后在异步任务返回结果的时候再根据一定规则去执行相应的回调  为什么js会设计成单线程和非阻塞？   原因：我们需要进行各种各样的dom操">
<meta property="og:type" content="article">
<meta property="og:title" content="JS事件循环">
<meta property="og:url" content="http://example.com/2020/11/03/jsCore/index.html">
<meta property="og:site_name" content="黑不溜球de博客么么哒">
<meta property="og:description" content="javascriptjavascript从诞生之日起就是一门单线程的非阻塞的脚本语言。这是由其最初的用途来决定的：与浏览器交互。  单线程：javascript代码在执行的任何时候，都只有一个主线程来处理所有的任务  非阻塞：执行异步任务的时候，主线程这个任务，然后在异步任务返回结果的时候再根据一定规则去执行相应的回调  为什么js会设计成单线程和非阻塞？   原因：我们需要进行各种各样的dom操">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://example.com/Users/niruoshangzaichang/Documents/js%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF.png">
<meta property="article:published_time" content="2020-11-03T06:36:12.664Z">
<meta property="article:modified_time" content="2020-11-03T06:37:20.736Z">
<meta property="article:author" content="Jone-xin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/Users/niruoshangzaichang/Documents/js%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF.png">
  
    <link rel="alternate" href="/my_blog/atom.xml" title="黑不溜球de博客么么哒" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/my_blog/css/style.css">

<meta name="generator" content="Hexo 5.2.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/my_blog/" id="logo">黑不溜球de博客么么哒</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/my_blog/">主页</a>
        
          <a class="main-nav-link" href="/my_blog/archives">归档</a>
        
          <a class="main-nav-link" target="_blank" rel="noopener" href="https://gitee.com/xiangxinag-darling">@我的gitee</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/my_blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-jsCore" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/my_blog/2020/11/03/jsCore/" class="article-date">
  <time datetime="2020-11-03T06:36:12.664Z" itemprop="datePublished">2020-11-03</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JS事件循环
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h1 id="javascript"><a href="#javascript" class="headerlink" title="javascript"></a>javascript</h1><p>javascript从诞生之日起就是一门<strong>单线程的非阻塞</strong>的脚本语言。这是由其最初的用途来决定的：与浏览器交互。</p>
<ul>
<li><p><strong>单线程</strong>：javascript代码在执行的任何时候，都只有一个主线程来处理所有的任务</p>
</li>
<li><p><strong>非阻塞</strong>：执行异步任务的时候，主线程这个任务，然后在异步任务返回结果的时候再根据一定规则去执行相应的回调</p>
</li>
<li><p><strong>为什么js会设计成单线程和非阻塞？</strong></p>
</li>
</ul>
<p>原因：我们需要进行各种各样的dom操作。试想一下 如果javascript是多线程的，那么当两个线程同时对dom进行一项操作，例如一个向其添加事件，而另一个删除了这个dom，此时该如何处理呢？javascript选择只用一个主线程来执行代码，这样就保证了程序执行的一致性。</p>
<ul>
<li><strong>js如何实现非阻塞</strong>？</li>
</ul>
<p>主角：<strong>event loop(事件循环)</strong></p>
<p><em>nodejs中的也存在与传统浏览器环境下的相似的事件循环。然而两者间却有着诸多不同，</em></p>
<h4 id="浏览器环境下js引擎的事件循环机制"><a href="#浏览器环境下js引擎的事件循环机制" class="headerlink" title="浏览器环境下js引擎的事件循环机制"></a><strong>浏览器环境下js引擎的事件循环机制</strong></h4><ul>
<li><p><strong>执行栈和事件队列</strong></p>
<blockquote>
<p><strong>执行栈</strong>：当我们调用一个方法的时候，js会生成一个与这个方法对应的执行环境（context），又叫执行上下文。这个执行环境中存在着这个方法的私有作用域，上层作用域的指向，方法的参数，这个作用域中定义的变量以及这个作用域的this对象。 而当一系列方法被依次调用的时候，因为js是单线程的，同一时间只能执行一个方法，于是这些方法被排队在一个单独的地方。这个地方被称为执行栈。</p>
<p><strong>事件队列</strong>：代码自上向下执行，遇到异步代码，就把异步代码放到事件队列中，直到执行栈里面没有任务，才会在事件队列中按顺序执行异步代码。</p>
</blockquote>
</li>
<li><p><strong>异步任务的分类</strong><br>1，macro task(宏任务)</p>
<ul>
<li><code>setInterval()</code></li>
<li><code>setTimeout()</code></li>
</ul>
<p>2，micro task(微任务)</p>
<ul>
<li><code>new Promise()</code></li>
<li><code>new MutaionObserver()</code></li>
</ul>
</li>
<li><p><strong>宏微任务的具体调用步骤</strong>：（当宏任务遇到微任务，先执行微任务）</p>
<p>我们以一段代码为例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">1</span>);</span><br><span class="line">  </span><br><span class="line">  	<span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">      consle.log(<span class="number">6</span>)</span><br><span class="line">    &#125;,<span class="number">0</span>)</span><br><span class="line">  	<span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve,reject</span>)</span>&#123;</span><br><span class="line">  	  <span class="built_in">console</span>.log(<span class="number">4</span>)</span><br><span class="line">    	resolve(<span class="number">5</span>)</span><br><span class="line">		&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">val</span>)</span>&#123;</span><br><span class="line">    			<span class="built_in">console</span>.log(val);</span><br><span class="line">			&#125;)</span><br><span class="line">&#125;,<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve,reject</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">2</span>)</span><br><span class="line">    resolve(<span class="number">3</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">val</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(val);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h5 id="步骤如下"><a href="#步骤如下" class="headerlink" title="步骤如下"></a>步骤如下</h5><p><img src="/Users/niruoshangzaichang/Documents/js%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF.png" alt="js事件循环"></p>
</li>
</ul>
<p>​      最后打印结果为：231456</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://example.com/2020/11/03/jsCore/" data-id="ckhmnwytz00036rx4bdal3py7" class="article-share-link">Share</a>
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/my_blog/2020/11/03/computer/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          计算机网路笔记
        
      </div>
    </a>
  
  
    <a href="/my_blog/2020/11/03/browser/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">浏览器发展史与现状</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/my_blog/archives/2020/11/">November 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/my_blog/archives/2020/10/">October 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/my_blog/2020/11/18/zhengze/">JS中的正则表达式</a>
          </li>
        
          <li>
            <a href="/my_blog/2020/11/03/react/">React基础知识笔记</a>
          </li>
        
          <li>
            <a href="/my_blog/2020/11/03/vue/">Vue基础知识笔记</a>
          </li>
        
          <li>
            <a href="/my_blog/2020/11/03/async/">JS异步编程的三种方案</a>
          </li>
        
          <li>
            <a href="/my_blog/2020/11/03/computer/">计算机网路笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 Jone-xin<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/my_blog/" class="mobile-nav-link">主页</a>
  
    <a href="/my_blog/archives" class="mobile-nav-link">归档</a>
  
    <a target="_blank" rel="noopener" href="https://gitee.com/xiangxinag-darling" class="mobile-nav-link">@我的gitee</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/my_blog/fancybox/jquery.fancybox.css">

  
<script src="/my_blog/fancybox/jquery.fancybox.pack.js"></script>




<script src="/my_blog/js/script.js"></script>




  </div>
</body>
</html>